// Describe:
package init

import (
	"github.com/rs/zerolog/log"
	"github.com/spf13/viper"
	"os"
	"os/exec"
	"path"
	"strings"
	"wormhole/utils"
)

/*
[core]
[log]

*/
func initConfig() {
	sourceDir, err := exec.LookPath(os.Args[0])
	if err != nil {
		log.Fatal().Err(err).Msg("无法检测程序目录")
	}
	sourceDir = strings.ReplaceAll(sourceDir, `\`, `/`)
	baseDir := path.Dir(sourceDir)
	viper.SetDefault("core.port", 1808)
	viper.SetDefault("core.store", path.Join(baseDir, "store"))
	viper.SetDefault("core.name", utils.NcInfo.Mac)
	viper.SetDefault("log.level", "info")
	viper.SetDefault("core.mode", "auto")
	viper.SetDefault("svc.progress", false)

	configDir := baseDir
	configFile := "wormhole.toml"
	logPath := path.Join(configDir, "wormhole.log")
	viper.SetDefault("log.path", logPath)

	configPath := path.Join(configDir, configFile)
	viper.SetConfigName(strings.Split(configFile, ".")[0])
	viper.SetConfigType(strings.Split(configFile, ".")[1])
	viper.AddConfigPath(configDir)

	if !utils.IsExistPath(configPath) {
		err := os.MkdirAll(configDir, 0777)
		err = viper.SafeWriteConfigAs(configPath)
		if err != nil {
			log.Fatal().Err(err).Msg("初始化配置失败")
		}
	}
	err = viper.ReadInConfig()
	if err != nil {
		log.Fatal().Err(err).Msg("读取配置文件失败")
	}
	viper.WatchConfig()
}
